import axios from 'axios'
import {isNull, eachProp} from '@/utils/Common'
import store from '@/store'

const service = axios.create({
    baseURL: '/',
    timeout: 30000
})

const header = {
    "content-type": "application/json;charset=UTF-8",
};

// request 拦截器
service.interceptors.request.use(originConfig => {
    const config = originConfig;
    const method = String(config.method).toUpperCase();
    config.headers["content-type"] = "application/json;charset=UTF-8";
    if (config.url.indexOf('/zms/') == -1) {
        let globalData = store.getters.globalData
        config.headers.Authorization = globalData.access_token ||  globalData.userToken;
        config.headers.bankCode = globalData.bankCode ||  "";
        config.headers.sessionId = globalData.sessionId ||  "";
    }

    if(method === 'POST'){

    } else if (method === 'GET') {
        config.url = wrapParamUrl(config.url, config.data)
    }
    return config
}, err => Promise.reject(err))

// response 拦截器
service.interceptors.response.use(response => {
    console.log(response);


    return response;
}, err => Promise.reject(err))

// get 请求,将data 包装到url上
function wrapParamUrl(originUrl, data){
    let url = `${originUrl}?`;
    if(data) {
        eachProp(data, prop => {
            if(!isNull(data[prop])) {
                url += `${prop}=${data[prop].toString()}&`
            }
        })
    }
    // S删除url中最后一个&
    url = url.substring(0, url.length - 1)
    return url;
}

export default service;